package account_manage

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go_gui/diy"
	"go_gui/g"
	"go_gui/lib"
	"golang.org/x/image/colornames"
	"strings"
	"time"
)

var refreshTime int64

// ServerInfoView 区服选择、活跃人数、总人数等
func ServerInfoView(gameInfo *GameInfo) fyne.CanvasObject {
	_loading := NewLoading("正在加载区服", 80).Show()
	// 获取区服列表
	_serverConfigList := GetServerConfigList(gameInfo.GameKey, "")
	// 加上g123正式服
	//if lib.InSlice(gameInfo.GameKey, G123GameKeyList) {
	//	_release_serverConfigList := GetServerConfigList(gameInfo.GameKey)
	//}
	_loading.Hide()

	// 生成下拉列表
	_selectList := make([]string, 0)
	// 存在默认的放在前面
	if gameInfo.DefaultServer != "" {
		for serverName, _ := range gameInfo.Server2Info {
			_selectList = append(_selectList, serverName)
		}
		// 记录内网详情
		DebugServerInfo = gameInfo.Server2Info[gameInfo.DefaultServer]

	}
	if len(_serverConfigList) > 0 {
		for _, serverConfig := range _serverConfigList {
			_serverName := serverConfig.ServerName
			if _serverName == "" {
				_serverName = "无区服名"
			}
			_serverName = fmt.Sprintf("%s(%s)", _serverName, serverConfig.ServerId)
			if lib.InSlice(gameInfo.GameKey, G123GameKeyList) {
				_serverName = fmt.Sprintf("%s(%s)", serverConfig.Owner, serverConfig.ServerName)
			}

			// 更新区服信息
			gameInfo.Server2Info[_serverName] = &serverInfo{
				Ver:      serverConfig.Cont.Ver,
				DbHost:   serverConfig.DbHost,
				Url:      fmt.Sprintf("mongodb://root:iamciniao@%s:27017", serverConfig.DbHost),
				DbName:   serverConfig.DbName,
				OpenTime: serverConfig.OpenTime,
			}
			if lib.InSlice(serverConfig.Game, G123GameKeyList) {
				var mongoUrl string
				switch serverConfig.Owner {
				case "测试服":
					mongoUrl = CurGameInfo.G123StgMongoUrl
				case "正式服":
					mongoUrl = CurGameInfo.G123ProMongoUrl

				}
				gameInfo.Server2Info[_serverName].Url = mongoUrl
				gameInfo.Server2Info[_serverName].DbName = fmt.Sprintf("%s_%s", serverConfig.Game, serverConfig.ServerId)
			}

			_selectList = append(
				_selectList,
				fmt.Sprintf(
					"%s %s owner:%s",
					_serverName,
					serverConfig.OpenTime,
					serverConfig.Owner,
				),
			)
		}
	}

	if len(_selectList) == 0 {
		_selectList = append(_selectList, "无区服信息")
	}

	var (
		_sumUserText    = canvas.NewText("", colornames.Red) // 区服总人数
		_activeUserText = canvas.NewText("", colornames.Red) // 今日活跃总人数
		_activeUserList []map[string]any
	)
	_serverSelectDo := func(s string) {
		_serverName := strings.Split(s, " ")[0]
		_serverInfo, ok := gameInfo.Server2Info[_serverName]
		// 有效的区服信息
		if ok {
			CurServerInfo = _serverInfo

			// mongo init
			InitMongo(_serverInfo)

			go func() {
				// 活跃玩家
				_option := &options.FindOptions{}
				_option.
					SetProjection(gudShowKey).
					SetSort(bson.M{
						"lv": -1,
					})
				var _activeKey string
				switch gameInfo.GameKey {
				case "heros":
					_activeKey = "hearttime"
				case "mfm_wechat":
					_activeKey = "hearttime"
				default:
					_activeKey = "lasttime"
				}

				_activeUserList = g.Mdb.Find(
					"userinfo",
					bson.M{_activeKey: bson.M{"$gte": g.C.Zero(g.C.Now())}},
					_option,
				)

				// 更新区服总人数和活跃人数
				_sumUserText.Text = g.C.Int64ToString(g.Mdb.Count("userinfo", bson.M{}))
				_sumUserText.Refresh()
				_activeUserText.Text = g.C.IntToString(len(_activeUserList))
				_activeUserText.Refresh()
			}()

		}

		if AccountComp.RankSelect != nil {
			AccountComp.RankSelect.OnChanged(AccountComp.RankSelect.Selected)
		}
		if AccountComp.SearchBindUidEntry != nil {
			AccountComp.SearchBindUidEntry.SetText("")
			AccountComp.BindUidResEntry.SetText("")
		}

	}
	// 区服选择下拉框
	_serverSelect := widget.NewSelect(_selectList, _serverSelectDo)
	// 默认选择第一个
	_serverSelect.SetSelectedIndex(0)
	AccountComp.ServerSelect = _serverSelect
	// 记录所有
	_allServerSelect := _selectList

	// 查询玩家信息
	_searchUserEntry := &widget.Entry{
		Wrapping:    fyne.TextWrapOff,
		PlaceHolder: "输入玩家uid查询详细信息",
		OnSubmitted: func(uid string) {
			ShowUserInfoView(uid)
		},
	}

	_activeUserIcon := diy.NewIcon(theme.VisibilityIcon())
	_createActiveUserWin := func() *widget.PopUp {
		if len(_activeUserList) == 0 {
			return nil
		}
		_showKeys := []string{"最后登录时间", "名字", "等级", "VIP", "战力", "binduid", "uid"}
		// 排行榜展示table
		_dataTable := widget.NewTable(
			func() (int, int) {
				return len(_activeUserList) + 1, len(_showKeys) + 1
			},
			func() fyne.CanvasObject {
				return diy.NewMenuLabel("")
			},
			func(id widget.TableCellID, cell fyne.CanvasObject) {
				menuLabel := cell.(*diy.MenuLabel)
				menuLabel.Clear()
				// 排名序列
				if id.Col == 0 {
					menuLabel.SetText(fmt.Sprintf("%d", id.Row+1))

				}

				// 表头
				if id.Row == 0 {
					if id.Col > 0 {
						menuLabel.SetText(fmt.Sprintf("%s", _showKeys[id.Col-1]))
					}
				} else {
					if id.Col >= 1 {
						_idx := id.Row - 1
						_setKey := _showKeys[id.Col-1]
						_toKey, ok := getKey2Val(_setKey)
						var _setVal string
						var anyVal any
						_userInfo := _activeUserList[_idx]
						if ok {
							anyVal = _userInfo[_toKey]
						} else {
							anyVal = _userInfo[_setKey]
						}
						switch _setKey {
						case "最后登录时间":
							_setVal = g.C.Now2Date(int64(anyVal.(int32)))
						default:
							_setVal = g.C.Any2String(anyVal)

						}
						menuLabel.SetText(_setVal)
						// 设置扩展按钮
						menuLabel.SetMenuItems(chkAppendMenuItems(_setKey, _setVal, _userInfo, cell)...)

					}
				}

			},
		)
		_dataTable.SetColumnWidth(0, 34)
		// 设置表头宽度
		for idx, key := range _showKeys {
			_dataTable.SetColumnWidth(idx+1, key2Width[key])
		}

		_popUp := widget.NewPopUp(
			_dataTable,
			fyne.CurrentApp().Driver().CanvasForObject(_activeUserIcon),
		)
		_popUp.Resize(fyne.NewSize(1010, 700))
		// 当前选择的控件左上角坐标
		_popUp.ShowAtPosition(
			fyne.CurrentApp().Driver().AbsolutePositionForObject(_activeUserIcon).
				Add(
					fyne.NewPos(-450, _activeUserIcon.Size().Height),
				),
		)
		return _popUp
	}

	// 区服扩展 筛选owner，区服搜索等
	_clickIcon := diy.NewIcon(theme.MenuIcon())
	_clickIcon.SetClickFunc(func(e *fyne.PointEvent) {
		_showPos := e.AbsolutePosition
		widget.ShowPopUpMenuAtPosition(
			fyne.NewMenu(
				"",
				initFilterOwnerMenuItem(_serverSelect, _allServerSelect, _showPos),
				findServerMenuItem(_serverSelect, _allServerSelect, _showPos),
			),
			fyne.CurrentApp().Driver().CanvasForObject(_activeUserIcon),
			_showPos,
		)

	})

	_refreshButton := &widget.Button{
		Text: "刷新 ",
	}
	_refreshFunc := func() {
		_nt := g.C.Now()
		if _nt-refreshTime <= 2 {
			diy.ShowSleepInfor(1, "刷新太频繁了,请稍后再试")
			return
		}
		refreshTime = _nt
		_serverSelectDo(_serverSelect.Selected)
		diy.ShowSleepInfor(1, "刷新成功!!")

		go func() {
			_refreshButton.Disable()
			_sleepTime := 3
			_refreshButton.Text = fmt.Sprintf("刷新%d", _sleepTime)
			_refreshButton.Refresh()
			_ticker := time.NewTicker(time.Second * 1)
			defer _ticker.Stop()
			for {
				select {
				case <-_ticker.C:
					_sleepTime--
					_refreshButton.Text = fmt.Sprintf("刷新%d", _sleepTime)
					_refreshButton.Refresh()
					if _sleepTime <= 0 {
						goto End
					}
				}
			}
		End:
			_refreshButton.Text = "刷新 "
			_refreshButton.Refresh()
			_refreshButton.Enable()
		}()
	}
	_refreshButton.OnTapped = _refreshFunc

	_view := container.NewHBox(
		widget.NewLabel("请选择区服:"),
		_serverSelect,
		diy.NewIcon(theme.VisibilityIcon()).
			SetLabelTextFunc(func() string { return _serverSelect.Selected }),
		_clickIcon,
		widget.NewLabel("区服总人数:"),
		_sumUserText,
		widget.NewLabel("今日活跃:"),
		_activeUserText,
		_activeUserIcon.
			SetShowWinFunc(_createActiveUserWin),
		widget.NewLabel(""),
		_searchUserEntry,
		widget.NewButton("查询", func() {
			ShowUserInfoView(_searchUserEntry.Text)
		}),
		//widget.NewLabel(""),
		layout.NewSpacer(),
		//widget.NewSeparator(),
		_refreshButton,
		widget.NewButton("数据库查询", func() {
			FindMongoView()
		}),
	)

	return _view
}

// initFilterOwnerMenuItem  初始化owner筛选
func initFilterOwnerMenuItem(serverSelect *widget.Select, allServerSelect []string, toPos fyne.Position) *fyne.MenuItem {
	_ownerMenuItemList := make([]*fyne.MenuItem, len(CurOwnerList)+1)
	_ownerMenuItemList[0] = fyne.NewMenuItem("显示所有", func() {
		serverSelect.Options = allServerSelect
		serverSelect.SetSelectedIndex(0)
		serverSelect.Refresh()
	})
	for idx, owner := range CurOwnerList {
		_curOwner := owner
		_ownerMenuItemList[idx+1] = fyne.NewMenuItem(owner, func() {
			_newSelectList := make([]string, 0)
			for _, s := range allServerSelect {
				if !strings.Contains(s, _curOwner) {
					continue
				}
				_newSelectList = append(_newSelectList, s)
			}
			serverSelect.Options = _newSelectList
			serverSelect.SetSelectedIndex(0)
			serverSelect.Refresh()
		})
	}

	_filterOwnerMenuItem := fyne.NewMenuItem("筛选owner", func() {
		popUp := widget.NewPopUpMenu(
			fyne.NewMenu("", _ownerMenuItemList...),
			fyne.CurrentApp().Driver().CanvasForObject(serverSelect),
		)
		popUp.ShowAtPosition(toPos)
		//popUp.Resize(fyne.NewSize(s.Size().Width, s.popUp.MinSize().Height))
	})

	return _filterOwnerMenuItem
}

// findServerMenuItem 通过sid或区服名查找区服
func findServerMenuItem(serverSelect *widget.Select, allServerSelect []string, toPos fyne.Position) *fyne.MenuItem {
	_filterOwnerMenuItem := fyne.NewMenuItem("区服查找", func() {
		_bindUidEntry := widget.NewEntry()
		_bindUidEntry.PlaceHolder = "通过sid或区服名查找区服"
		_form := diy.NewForm(
			AccountComp.GameView,
			func() {
				_searchData := _bindUidEntry.Text
				_newSelectList := make([]string, 0)
				for i := 0; i < 2; i++ {
					if i == 1 {
						_searchData = fmt.Sprintf("(%s)", _searchData)
					}
					for _, s := range allServerSelect {
						if !strings.Contains(s, _searchData) {
							continue
						}
						_newSelectList = append(_newSelectList, s)
					}
				}
				if len(_newSelectList) <= 0 {
					diy.ShowSleepInfor(2, "未找到相关区服")
					return
				}
				serverSelect.Options = _newSelectList
				serverSelect.SetSelectedIndex(0)
				serverSelect.Refresh()
			},
			func() string {
				if _bindUidEntry.Text == "" {
					return "搜索数据为空!"
				}

				return "success"
			},
			"区服查找",
			true,
			diy.NewFormItem("", _bindUidEntry),
		)
		_bindUidEntry.OnSubmitted = _form.DoSubmit
		_form.Resize(fyne.NewSize(500, 0))
		_form.ShowAtPosition(toPos)

	})

	return _filterOwnerMenuItem
}

// IsNoServer 判断是否无区服
func IsNoServer() bool {
	if AccountComp.ServerSelect == nil {
		return true
	}

	if AccountComp.ServerSelect.Options[0] == "无区服信息" {
		return true
	}

	return false
}
